//
//  NSObject+MapNavigation.m
//  KX11UI
//
//  Created by HYC on 2021/2/24.
//

#import "NSObject+Tools_HYC_Neusoft.h"
#import "MapNavigationModel.h"
#import "ZLVH_ChooseMapView.h"

#import <MapKit/MapKit.h>


//#import <BMKLocationkit/BMKLocationComponent.h>
//#import <BaiduMapAPI_Base/BMKBaseComponent.h>
//#import <BaiduMapAPI_Map/BMKMapComponent.h>


@implementation NSObject (Tools_HYC_Neusoft)



- (NSArray *)bd09LLToGPSLat:(double)glat lon:(double)glon {
    
    NSArray *arr = [self bd09llToGCJLat:glat lon:glon];
    
    return [self gcjToWGS:arr];
    
}
/**
 百度坐标转高德坐标

 @param glat 纬度
 @param glon 经度
 @return 数组【转换后的纬度，转换后的经度】
 */
- (NSArray *)bd09llToGCJLat:(double)glat lon:(double)glon {
    double X_PI = M_PI * 3000.0 / 180.0;
    double x = glon - 0.0065;
    double y = glat - 0.006;
    double z = sqrt(x * x + y * y) - 0.00002 * sin(y * X_PI);
    double theta = atan2(y, x) - 0.000003 * cos(x * X_PI);
    double lat = z * sin(theta);
    double lon = z * cos(theta);
    NSArray *latlon = @[[NSNumber numberWithDouble:lat],[NSNumber numberWithDouble:lon]];
    
    return latlon;
}
/**
 高德坐标转系统自带坐标

 @param array 数组 需要转换的坐标【纬度，经度】
 @return 数组【转换后的纬度，转换后的经度】
 */
- (NSArray *)gcjToWGS:(NSArray *)array {
    double lat = [array.firstObject doubleValue];
    double lon = [array.lastObject doubleValue];
    if ([self outOfChinalat:lat lon:lon]){
        return @[[NSNumber numberWithDouble:lat],[NSNumber numberWithDouble:lon]];
    }
    NSArray *latlon = [self deltalat:lat lon:lon];
    return latlon;
}

- (BOOL)outOfChinalat:(double)lat lon:(double)lon {
    if (lon < 72.004 || lon > 137.8347)
        return true;
    if (lat < 0.8293 || lat > 55.8271)
        return true;
    return false;
}

- (NSArray *)deltalat:(double)wgLat lon:(double)wgLon {
    double OFFSET = 0.00669342162296594323;
    double AXIS = 6378245.0;
    
    double dLat = [self transformLatx:(wgLon - 105.0) lon:(wgLat - 35.0)];
    double dLon = [self transformLonx:(wgLon - 105.0) lon:(wgLat - 35.0)];
    double radLat = wgLat / 180.0 * M_PI;
    double magic = sin(radLat);
    magic = 1 - OFFSET * magic * magic;
    double sqrtMagic = sqrt(magic);
    dLat = (dLat * 180.0) / ((AXIS * (1 - OFFSET)) / (magic * sqrtMagic) * M_PI);
    dLon = (dLon * 180.0) / (AXIS / sqrtMagic * cos(radLat) * M_PI);
    return @[[NSNumber numberWithDouble:(wgLat - dLat)],[NSNumber numberWithDouble:(wgLon - dLon)]];
}

- (double)transformLatx:(double)x lon:(double)y {
    double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(abs(x));
    ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0;
    ret += (20.0 * sin(y * M_PI) + 40.0 * sin(y / 3.0 * M_PI)) * 2.0 / 3.0;
    ret += (160.0 * sin(y / 12.0 * M_PI) + 320 * sin(y * M_PI / 30.0)) * 2.0 / 3.0;
    return ret;
}

- (double)transformLonx:(double)x lon:(double)y {
    double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(abs(x));
    ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0;
    ret += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0;
    ret += (150.0 * sin(x / 12.0 * M_PI) + 300.0 * sin(x / 30.0 * M_PI)) * 2.0 / 3.0;
    return ret;
}

- (void)addLast_One_km_alertWithCoord:(CLLocationCoordinate2D)coord andEndName:(NSString *)endName andMapImageUrl:(NSString *)mapImageUrl {
    
    @weakify(self);
    [ZLVH_SY_AlertUntil showTextAlertView:@"开始导航" message:@"您收到一个来自车机目的地的信息" cancel:@"取消" sure:@"确认" cancelHandler:^(UIGestureRecognizer * _Nonnull action) {
            
            
            
        } sureHandler:^(UIGestureRecognizer * _Nonnull tap) {
            
            
            [ZLVH_ChooseMapView showViewWithTitleArray:@[@"高德地图",@"百度地图"] sureBlock:^(int index) {
                switch (index) {
                    case 0:{

                        if(![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]){
                            [ZLVH_HYC_Toast showMsg:@"您还未安装高德地图"];
                            return;
                        }

                        @strongify(self);
                        NSURL * gaode_App = [NSURL URLWithString:@"iosamap://"];
                        if ([[UIApplication sharedApplication] canOpenURL:gaode_App]) {
        //                    NSString *slat = [@(self.userLocation.location.coordinate.latitude) stringValue];
        //                    NSString *slon = [@(self.userLocation.location.coordinate.longitude) stringValue];
                            NSString *appName = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleDisplayName"];
                            NSString *strLatitude = [@(coord.latitude) stringValue];
                            NSString *strLongitude = [@(coord.longitude) stringValue];
                            NSString *address = endName;
                            
                            //&slat=%@ &slon=%@  slat   slon
                            NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=%@&sid=&sname=&did=&dlat=%@&dlon=%@&dname=%@&dev=0&t=0",appName,strLatitude,strLongitude,address] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:nil completionHandler:^(BOOL success) {}];
                        }
                    }break;
                        
                    default:{
                        
                        

                        
                        @strongify(self);
                        NSURL * bd_App = [NSURL URLWithString:@"baidumap://"];
                        if ([[UIApplication sharedApplication] canOpenURL:bd_App]) {
        //                    NSString *slat = [@(self.userLocation.location.coordinate.latitude) stringValue];
        //                    NSString *slon = [@(self.userLocation.location.coordinate.longitude) stringValue];
                            NSString *appName = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleDisplayName"];
                            
                            NSArray <NSNumber *>*GPSArr = [self bd09llToGCJLat:coord.latitude
                                                                           lon:coord.longitude
                                                           ];
                            
                            
                            
                            
                            NSString *dLat = GPSArr.firstObject.stringValue;
                            NSString *dLon = GPSArr.lastObject.stringValue;
                            NSString *address = endName;
                            
                            //origin=%@,%@&    ,slat,slon
                            NSString *urlString =[[NSString stringWithFormat:@"baidumap://map/direction?destination=name:%@|latlng:%@,%@&coord_type=bd09ll&mode=driving&src=ios.%@.%@",address,dLat,dLon,appName,appName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                            
                            
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:nil completionHandler:^(BOOL success) {}];
                            
                            
                        }
                        
                        
                        if(![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]){
                            [ZLVH_HYC_Toast showMsg:@"您还未安装百度地图"];
        
                            return;
                        }
                        
                    }break;
                }
            } cancelBlock:nil];
            
        }];
    
    
}


//根据polyline设置地图范围
- (void)mapViewFitPolyline:(BMKPolyline *)polyline withMapView:(BMKMapView *)mapView withUIEdgeInsets:(UIEdgeInsets)edgeInsets {
    double leftTop_x, leftTop_y, rightBottom_x, rightBottom_y;
    if (polyline.pointCount < 1) {
        return;
    }
    
    
    
    
    
    BMKMapPoint pt = polyline.points[0];
    leftTop_x = pt.x;
    leftTop_y = pt.y;
    //左上方的点lefttop坐标（leftTop_x，leftTop_y）
    rightBottom_x = pt.x;
    rightBottom_y = pt.y;
    //右底部的点rightbottom坐标（rightBottom_x，rightBottom_y）
    for (int i = 1; i < polyline.pointCount; i++) {
        BMKMapPoint point = polyline.points[i];
        if (point.x < leftTop_x) {
            leftTop_x = point.x;
        }
        if (point.x > rightBottom_x) {
            rightBottom_x = point.x;
        }
        if (point.y < leftTop_y) {
            leftTop_y = point.y;
        }
        if (point.y > rightBottom_y) {
            rightBottom_y = point.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(leftTop_x , leftTop_y);
    rect.size = BMKMapSizeMake(rightBottom_x - leftTop_x, rightBottom_y - leftTop_y);
    UIEdgeInsets padding = edgeInsets;
    [mapView fitVisibleMapRect:rect edgePadding:padding withAnimated:YES];
}

- getMapCLPlacemarkWithLat:(CGFloat)lat WithLog:(CGFloat)log WithAMapCoordinateType:(BMK_COORD_TYPE)type success:(void (^)(BMKReverseGeoCodeSearchResult *result))success error:(void (^)(BMKSearchErrorCode * _Nullable error))errors {

//    // 国测局坐标类型的原始坐标
//    CLLocationCoordinate2D gcj02Coord = CLLocationCoordinate2DMake(39.90868, 116.3956);
//    // 转为百度经纬度类型的坐标
//    CLLocationCoordinate2D bd09Coord = BMKCoordTrans(gcj02Coord, BMK_COORDTYPE_COMMON, BMKCOORDTYPE_BD09LL);
    [[[GEE_AMapSearchD sharedManager] searchReverseWith:lat With:log] setSearchCLPlacemarkBlock:^(BMKReverseGeoCodeSearchResult * _Nonnull result, BMKSearchErrorCode * _Nonnull error) {
        
        if (error == BMK_SEARCH_NO_ERROR) {
            //在此处理正常结果
            
            BMKReverseGeoCodeSearchResult *resultt2 = result;
            resultt2.location = CLLocationCoordinate2DMake(lat, log);
            
            success(resultt2);
        }
        else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD) {
            NSLog(@"检索词有歧义");
            
            success(result);
        } else {
            
            errors(error);
            NSLog(@"其他检索结果错误码相关处理");
        }
        
        

        
    }];
    



    return self;
}

- getMapPOIsWithRequest:(BMKPOINearbySearchOption *)request success:(void (^)(BMKPOISearchResult *result))success error:(void (^)(BMKSearchErrorCode * _Nullable error))errors {
    
    [[[GEE_AMapSearchD sharedManager] searchPOINearbyWith:request] setSearchPOIResultBlock:^(BMKPOISearchResult * _Nonnull result, BMKSearchErrorCode * _Nonnull error) {
            
        if (error == BMK_SEARCH_NO_ERROR) {
            //在此处理正常结果
            success(result);
        }
        else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD) {
            NSLog(@"检索词有歧义");
            
            success(result);
        } else {
            
            errors(error);
            NSLog(@"其他检索结果错误码相关处理");
        }
            
    }];
    
    return self;
}

- getMapSUGWithKey:(NSString *)name WithCity:(NSString *)cityName WithCoo:(CLLocationCoordinate2D)coord success:(void (^)(BMKSuggestionSearchResult *result))success error:(void (^)(BMKSearchErrorCode * _Nullable error))errors {
    
    [[GEE_AMapSearchD.sharedManager searchSUGWithStr:name WithCity:cityName withCoo:coord] setSearchSUGResultBlock:^(BMKSuggestionSearchResult * _Nonnull result, BMKSearchErrorCode * _Nonnull error) {
            
        if (error == BMK_SEARCH_NO_ERROR) {
            //在此处理正常结果
            success(result);
        }
        else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD) {
            NSLog(@"检索词有歧义");
            
            success(result);
        } else {
            
            errors(error);
            NSLog(@"其他检索结果错误码相关处理");
        }
            
    }];
    
    return self;
}

/// 线路规划
- getMapRouteWithStart:(BMKPlanNode *)start End:(BMKPlanNode *)end success:(void (^)(BMKDrivingRouteResult *result))success error:(void (^)(BMKSearchErrorCode * _Nullable error))errors {
    
    [[GEE_AMapSearchD.sharedManager searchRouteWithBMKPlanNodeStart:start End:end] setSearchRouteResultBlock:^(BMKDrivingRouteResult * _Nonnull result, BMKSearchErrorCode * _Nonnull error) {
        
        if (error == BMK_SEARCH_NO_ERROR) {
            //在此处理正常结果
            success(result);
        }
        else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD) {
            NSLog(@"检索词有歧义");
            
            success(result);
        } else {
            
            errors(error);
            NSLog(@"其他检索结果错误码相关处理");
        }
        
    }];
    
    return self;
}
//
//
@end
//
//
//
@interface GEE_AMapSearchD()<BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate,BMKRouteSearchDelegate>//<AMapSearchDelegate>
//
//@property (nonatomic,strong)AMapSearchAPI *search;
@property (nonatomic,strong)BMKGeoCodeSearch *search;
//BMKPoiSearch *poiSearch = [[BMKPoiSearch alloc] init];
@property (nonatomic,strong)BMKPoiSearch *poiSearch;
//BMKSuggestionSearch *search = [[BMKSuggestionSearch alloc] init];
@property (nonatomic,strong)BMKSuggestionSearch *sugSearch;
//BMKRouteSearch *routeSearch = [[BMKRouteSearch alloc] init];
@property (nonatomic,strong)BMKRouteSearch *routeSearch;
//
@end
@implementation GEE_AMapSearchD
+ (GEE_AMapSearchD *)sharedManager
{
    static GEE_AMapSearchD *sharedAccountManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedAccountManagerInstance = [[self alloc] init];
    });
    return sharedAccountManagerInstance;
}
- (instancetype)init
{
    self = [super init];
    if (self) {

//        self.search = [[AMapSearchAPI alloc] init];
        self.search                 = BMKGeoCodeSearch.alloc.init;
        self.poiSearch              = BMKPoiSearch.alloc.init;
        self.sugSearch              = BMKSuggestionSearch.alloc.init;
        self.routeSearch            = BMKRouteSearch.alloc.init;
        
        self.poiSearch.delegate     = self;
        self.search.delegate        = self;
        self.sugSearch.delegate     = self;
        self.routeSearch.delegate   = self;
        

    }
    return self;
}
// MARK: - 百度逆地理编码代理
- searchReverseWith:(CGFloat)latitude_AMap With:(CGFloat)longitude_AMap {

    
    BMKReverseGeoCodeSearchOption *reverseGeoCodeOption = [[BMKReverseGeoCodeSearchOption alloc]init];
    reverseGeoCodeOption.location = CLLocationCoordinate2DMake(latitude_AMap, longitude_AMap);
    // 是否访问最新版行政区划数据（仅对中国数据生效）
    reverseGeoCodeOption.isLatestAdmin = YES;
//    reverseGeoCodeOption.extensionsRoad = true;
//    reverseGeoCodeOption.tags = @[@"建筑"];
//    reverseGeoCodeOption.pageSize = 10;
//    reverseGeoCodeOption.pageNum = 0;
    
    BOOL flag = [self.search reverseGeoCode: reverseGeoCodeOption];
    if (flag) {
        NSLog(@"逆geo检索发送成功");
    }  else  {
        NSLog(@"逆geo检索发送失败");
    }
    

    return self;
}
// MARK: - 百度POI搜索
- searchPOINearbyWith:(BMKPOINearbySearchOption *)poiNearby {

    
    
    BOOL flag = [self.poiSearch poiSearchNearBy:poiNearby];
    if (flag) {
        NSLog(@"POI周边检索成功");
    } else {
        NSLog(@"POI周边检索失败");
    }
    

    return self;
}
// MARK: - 百度SUG搜索
- searchSUGWithStr:(NSString *)searchStr WithCity:(NSString *)cityName withCoo:(CLLocationCoordinate2D)coord{

    
    
    BMKSuggestionSearchOption* option = [[BMKSuggestionSearchOption alloc] init];

    option.cityname = cityName;
    option.keyword  = searchStr;
    option.location = coord;
    option.cityLimit = false;
    
    BOOL flag = [self.sugSearch suggestionSearch:option];
    if (flag) {
        NSLog(@"Sug检索发送成功");
    }  else  {
        NSLog(@"Sug检索发送失败");
    }

    return self;
}

- searchRouteWithBMKPlanNodeStart:(BMKPlanNode *)start End:(BMKPlanNode *)end{
    
    
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = start;
    drivingRouteSearchOption.to = end;
    
    
    BOOL flag = [self.routeSearch drivingSearch: drivingRouteSearchOption];
    if (flag) {
        NSLog(@"驾车规划检索发送成功");
    } else{
        NSLog(@"驾车规划检索发送失败");
    }
    
    return self;
}
/**
 正向地理编码检索结果回调
 
 @param searcher 检索对象
 @param result 正向地理编码检索结果
 @param error 错误码，@see BMKCloudErrorCode
 */
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error {
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
    } else {
        NSLog(@"检索失败");
    }
}
/**
 反向地理编码检索结果回调
 
 @param searcher 检索对象
 @param result 反向地理编码检索结果
 @param error 错误码，@see BMKCloudErrorCode
 */
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error {
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        
        self.searchCLPlacemarkBlock?self.searchCLPlacemarkBlock(result, error):self.searchCLPlacemarkBlock;
    } else {
        NSLog(@"检索失败");
    }
}
#pragma mark - BMKPoiSearchDelegate
/**
 *返回POI搜索结果
 *@param searcher 搜索对象
 *@param poiResult 搜索结果列表
 *@param errorCode 错误码，@see BMKSearchErrorCode
 */
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPOISearchResult*)poiResult errorCode:(BMKSearchErrorCode)errorCode {
    //BMKSearchErrorCode错误码，BMK_SEARCH_NO_ERROR：检索结果正常返回
    
    self.searchPOIResultBlock?self.searchPOIResultBlock(poiResult, errorCode):self.searchPOIResultBlock;
    
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        NSLog(@"检索结果返回成功：%@",poiResult.poiInfoList);
        
        
    }
    else if (errorCode == BMK_SEARCH_AMBIGUOUS_KEYWORD) {
        NSLog(@"检索词有歧义");
    } else {
        NSLog(@"其他检索结果错误码相关处理");
    }
}

/**
 *返回suggestion搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结果
 *@param error 错误号，@see BMKSearchErrorCode
 */
- (void)onGetSuggestionResult:(BMKSuggestionSearch*)searcher result:( BMKSuggestionSearchResult*)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        NSLog(@"%f",result.suggestionList.lastObject.location.latitude);
        
        self.searchSUGResultBlock?self.searchSUGResultBlock(result, error):self.searchSUGResultBlock;
        
        
    }
    else {
        NSLog(@"检索失败");
    }
}

/**
 *返回驾车搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结果，类型为BMKDrivingRouteResult
 *@param error 错误号，@see BMKSearchErrorCode
 */
- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error {
    NSLog(@"onGetDrivingRouteResult error:%d", (int)error);
    if (error == BMK_SEARCH_NO_ERROR) {
        
        self.searchRouteResultBlock?self.searchRouteResultBlock(result, error):self.searchRouteResultBlock;
        
        //成功获取结果
    } else {
        //检索失败
    }
}
@end
